6.2 Form handling and regular expressions

  1. Motivations
    • How to submit multiple values with one name to a server-side script? Here is an example.
      Favourite courses:
      Cars:
    • How to check if the format of an email address is correct? Here is an example.
      Email address:
    • How to check if the format of a phone number is correct?
    • How to enforce the user to input important input fields?
    • How to enforce the user to use complex passwords? Here is an example.
      Minimum 4 character password:

  2. [You may skip this topic.] How to deal with any error in the user input? Read all in PHP 5 Form Validation. Let's discuss another time these real security issues in web application, such as Cross Site Scripting (XSS).
    • List different input types and input-like elements.
    • What is $_SERVER['PHP_SELF']?
    • Can you interpret action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>"?
    • Do you need to send the form data to the same PHP program that displayed the current client? Is there any benefit?
      • When only one PHP program is used for the user input and when the user inputs wrong data, the PHP program might display the same input form with some error messages and the user input should be sent to the same PHP program.
    • What does htmlspecialchars() do?
    • What is the benefit to use htmlspecialchars()?

  3. How to send multiple data with one name with the checkbox-type input and the select elements?
    ...
    <?php
    ...
    if (empty($_POST["courses"])) {
        $coursesErr = "Courses are required";
    } else {
        $aCourses = $_POST['courses'];
        $courses = '';
        for ($i = 0; $i < count($aCourses); $i++)  // or count($_POST['courses'])
            $courses .= $aCourses[$i] . ' ';  // or $_POST['courses'][$i++]
    }
    ...
    ?>
    ...
    <form ...>
    Courses:
    <input type="checkbox" name="courses[]" value="COMP2680">COMP2680
    <input type="checkbox" name="courses[]" value="COMP3540">COMP3540
    <input type="checkbox" name="courses[]" value="COMP4620">COMP4620
    <span class="error">* <?php echo $coursesErr;?></span>
    <br>
    Cars:
    <select name="cars[]" multiple>
        <option value="volvo">Volvo</option>
        <option value="saab">Saab</option>
        <option value="opel">Opel</option>
        <option value="audi">Audi</option>
    </select>
    </form>
    ...
    $.post(..., { 'courses[]': ['volvo', 'open']}, function(data) {...});
    ...
    

  4. Trial 1: Let's try to submit multiple values with one name.



  5. [You may skip this topic.] How to deal with required input fields? Read all in PHP 5 Forms - Required Fields.
    • In a PHP program, how can you check if the program is executed for the first time? Here is an example.
      • The initial HTML content generated by the PHP code includes
        <input type='hidden' name:'first' value:'true'>
        
      • The next HTML content generated by the PHP code includes
        <input type='hidden' name:'first' value:'false'>
        
    • In a PHP program, how can you check if an input field is empty?
    • When you redisplay the form with error messages, how can you display the values that the user already correctly entered? In the example in the above link, let's assume that the user entered only E-mail and submitted the form. I would like to see the E-mail address in the form redisplayed by the PHP program. What can you do here?
    • Here is an example for the above question.
    • Here is another example that solves the above question.
    • How are they different?
    • When the form is submitted with errors or empty fields, the error messages are displayed. Are only the error messages redisplayed? Is the entire page redisplayed?
    • Is it possible to use HTML, not PHP, for required input elements?
      • Yes.

  6. [You may skip this topic.] Read all in PHP 5 Complete Form Example.

  7. How to validate the format of user inputs - regular expression
    • Read all in PHP 5 Forms - Validate E-mail and URL.
      • How do you interpret the regular expression in preg_match()?
      • How do you interpret the regular expression in filter_var()?
    • Read carefully Steps1 and 2 in PHP regular expression tutorial.
      • There are two types of regular expressions. What type is used in PHP?
      • What symbol is used to as a delimiter in PHP regular expressions?
      • List the five groups of characters in a pattern. Can you explain how {}, [], and () are different?
      • Does '/^world$/' match 'world world'?
        NO
      • Does '/earth|world/' match 'world'?
        YES
      • Can you make a regular expression for PHP identifiers?
      • Trial 2: Let's try to use a regular expression to check the validity of identifiers. Identifiers should use only letters, digits, and '_'. They cannot start with a digit.


      • Can you make a regular expression for phone numbers?
      • Can you make a regular expression for usernames in TRUQA and TRU Messenger?
      • Trial 3: Let's try to use a regular expression to check the validity of username. Usernames should be minimum 4 characters. Only letters, digits, '_' and '$' can be used.


      • Can you make a regular expression for hexadecimal color codes?
    • Use of preg_match_all().
    • Check the third parameter in preg_match_all(). How do you interpret array &$matches?
    • Use of filter_var() for FILTER_VALIDATE_EMAIL and FILTER_VALIDATE_URL.

  8. Can you make a regular expression for passwords in TRUQA and TRU Messenger?
    • E.g., passwords should be
      • The password should have between six and fifteen word characters.
      • It should include at least one special character.
      • It should include at least one digit.
      • It should include at least one uppercase letter.
    • How?
    • Assertions are very useful tools, especially password like patterns.
      • Positive look-ahead: (?=PATTERN_HERE) should be in the next following pattern.
      • Negative look-ahead: (?!PATTERN_HERE) should not be in the next following pattern.
      • Here is an example for strong passwords.
        $password_pattern = '/^(?=.*[!@#$%^&*()\-_+=])(?=.*[0-9]) ...$/'    Be careful with .* in the assertions.
        if (preg_match($password_pattern, $password))
            ...
        else
            ...
        
        (?=.*[!@#$%^&*()\-_+=]) means there should be [!@#$%^&*()\-_+=] (i.e., a special character) after .* (i.e., any characters).
        (?=.*[0-9]) means there should be [0-9] (i.e., a digit) after .* (i.e., any characters).
      • Assertions usually appear in the beginning of regular expressions.
    • Trial 4: Let's try to use a regular expression to check if a given password follows the rules. Rules: minimum 6, at least one special character, at least one letter.


    • Trial 4.5: Let's try to use a regular expression to check if a given password follows the rules. Rules: minimum 6, maximum 12, at least one special character, at least one digit. The password should start with a digit.



  9. Regular expression with JavaScript
    • How to get the client timezone in PHP code?
      • Get the client timezone using JavaScript. How?
        // An example of a regular expression for passwords
        var p = "Abc!123";
        var regExpPassword = /^(?=.*[0-9]).{5,}$/;  // Regular expressions are objects in JS.
        var result = regExpPassword.test(p);
        alert(result);
        // Another example to extract patterns
        var d = new Date();
        var n = d.toTimeString();  // n includes the timezone. E.g., 11:22:54 GMT-0800 (Pacific Standard Time)
        alert(n);
        var regExp = /\(.*\)/;  // It is NOT a string. Is it a sort of object?
        var matches = n.match(regExp);
        alert(matches[0].substr(1, matches[0].length - 2));  // matches[0] includes this string "(...)".
        
      • Send the timezone to the server using Ajax.
    • Read all in JavaScript Regular Expressions, JavaScript String match() Method, and JavaScript RegExp Reference.
      • Is it possible to use the metacharacters, such as \d and \s, in PHP?
        Yes
      • Trial 5: Let's try to display all the numbers in a text. (Hint. .test() and .match())


    • Can you check usernames, passwords, and email addresses in your client-side code? Any good idea?
      • First of all, you need to capture the click event on the submit button.
      • If you use <input type='submit' ...>, the form will submit inputs to the action URL. You'd better use <input type='button' ...> instead, so that even when the user clicks the button, the form does not submit inputs automatically.
      • How to submit the form in JavaScript code then?
        <script>
            ???.???('test_form_button').???('click', function() {
                ???.???('???').submit();  // submit() method in the form object
            });
        </script>
        <form id='test_form' action='controller.php'>
            Username: <input id='username' type='text' name='username'><br>
            Password: <input id='password' type='???' name='password'><br>
            <input id='test_form_button' type='???' value='Submit'>  // Just button, not submit
                                                                     // If submit button is used, the click event may not be captured.
        </form>
        
      • How to use regular expressions in JavaScript code then?
        // Example of username
            ???.???('test_form_button').???('click', function() {
                if (!(/^[_a-z][_a-z0-9]{3,}$/i).???(???.???('username').value)) {  // Wrong
                    ...
                }
                else
                    ???.???('???').submit();  // submit() method in the form object
                // or
                var pattern = /^[_a-z][_a-z0-9]{3,}$/i;
                if (pattern.???(????('username').value))
                    ...
            }
        
    • How to force users to enter inputs always?
      The required attribute
    • Can you include a regular expression into an input element?
      The pattern attribute. Read HTML <input> pattern Attribute for further information/examples. It is interesting and can be used in SPA.
      <form id='test_form' action='controller.php'>
          Username: <input id='username' type='text' name='username'><br>
          Password: <input id='password' type='???' name='password' pattern='^[_a-z][_a-z0-9]{3,}$'><br>
          <input id='test_form_button' type='???' value='Submit'>  // Just button, not submit
                                                                   // If submit button is used, the click event may not be captured.
      </form>
      

  10. Learning outcomes
    • Use of controller for different user inputs.
    • How to display any error message with the original input forms.
    • Use of regular expressions to validate the syntax of user inputs such as password, email, phone numbers, and usernames.